package com.love.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.cloud.admin.api.constants.SelectTypeConstants;
import com.love.cloud.admin.api.dto.CustomGroupDto;
import com.love.cloud.admin.api.dto.CustomGroupUnionDto;
import com.love.cloud.admin.api.entity.SysCustomGroup;
import com.love.cloud.admin.api.entity.SysCustomGroupRelation;
import com.love.cloud.admin.api.vo.CustomGroupChangeVo;
import com.love.cloud.admin.mapper.SysCustomGroupMapper;
import com.love.cloud.admin.mapper.SysCustomGroupRelationMapper;
import com.love.cloud.admin.service.SysCustomGroupService;
import com.love.cloud.common.core.exception.BusinessException;
import com.love.cloud.common.security.service.SosUser;
import com.love.cloud.common.security.util.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hongdongqu
 */
@Service
public class SysCustomGroupServiceImpl extends ServiceImpl<SysCustomGroupMapper, SysCustomGroup> implements SysCustomGroupService {
    @Resource
    private SysCustomGroupRelationMapper sysCustomGroupRelationMapper;

    @Override
    public Object saveData(SysCustomGroup sysCustomGroup) {
        SosUser user = SecurityUtils.getUser();
        if(user==null){
            throw new BusinessException("获取到当前用户信息为空");
        }
        sysCustomGroup.setBelongUserId(user.getId());
        this.save(sysCustomGroup);
        return sysCustomGroup;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object change(CustomGroupChangeVo customGroupChangeVo) {
        List<Map<String,Object>> sysCustomGroupRelationList = customGroupChangeVo.getSysCustomGroupRelationList();
        //直接物理删除原来的数据
        QueryWrapper<SysCustomGroupRelation> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysCustomGroupRelation::getGroupId,customGroupChangeVo.getGroupId());
        sysCustomGroupRelationMapper.deletePhysicsById(queryWrapper);
        Integer sort = 1;
        if(sysCustomGroupRelationList!=null&&sysCustomGroupRelationList.size()>0){
            //新增最新的数据
            for (Map<String,Object> map: sysCustomGroupRelationList) {
                SysCustomGroupRelation relation = new SysCustomGroupRelation();
                String groupType = String.valueOf(map.get("type"));
                String id = String.valueOf(map.get("id"));
                Long uniqueId = Long.valueOf(SelectTypeConstants.USER.equals(groupType) ? id.split("_")[0] : id);
                String auxiliaryId = SelectTypeConstants.USER.equals(groupType) ? id.split("_")[1] : null;
                relation.setUniqueId(uniqueId);
                relation.setAuxiliaryId(auxiliaryId);
                relation.setType(groupType);
                relation.setGroupId(customGroupChangeVo.getGroupId());
                // 递增
                relation.setSort(sort++);
                sysCustomGroupRelationMapper.insert(relation);
            }
        }
        return "保存成功";
    }

    @Override
    public List<CustomGroupDto> getGroupDataByUserId(Long userId) {
        if(userId==null){
            throw new BusinessException("请传入用户id");
        }
        //返回的数据集合
        List<CustomGroupDto> customGroupDtoList=new ArrayList<>();
        QueryWrapper<SysCustomGroup> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysCustomGroup::getBelongUserId,userId)
            .orderByDesc(SysCustomGroup::getCreateTime);
        //设置子项

        List<SysCustomGroup> groups = this.list(queryWrapper);
        for (SysCustomGroup sysCustomGroup:groups) {
            QueryWrapper unionQueryWrapper=new QueryWrapper();
            unionQueryWrapper.eq("cr.group_id", sysCustomGroup.getId());
            unionQueryWrapper.orderByAsc("cr.sort");
            unionQueryWrapper.orderByDesc("cr.create_time");
            List<CustomGroupUnionDto> customGroupUnionDtoList = this.baseMapper.systemCustomGroupUnionJdbc(unionQueryWrapper);
            CustomGroupDto customGroupDto=new CustomGroupDto();
            customGroupDto.setId(sysCustomGroup.getId());
            customGroupDto.setName(sysCustomGroup.getName());
            //子成员
            List<Map<String, Object>> children = new ArrayList<>();
            for (CustomGroupUnionDto customGroupUnionDto:customGroupUnionDtoList) {
                String id = null;
                String name = null;
                String mobile = null;
                String sort = null;
                String position = null;
                switch (customGroupUnionDto.getType()) {
                    case "dept":
                        // 部门
                        id = String.valueOf(customGroupUnionDto.getUniqueId());
                        name = String.valueOf(customGroupUnionDto.getDeptName());
                        sort = String.valueOf(customGroupUnionDto.getDeptSort());
                        break;
                    case "user":
                        // 用户
                        id = customGroupUnionDto.getUniqueId() + "_" +customGroupUnionDto.getAuxiliaryId();
                        name = customGroupUnionDto.getUserName()+ "(" +customGroupUnionDto.getUserDeptName() +")";
                        position = customGroupUnionDto.getUserPosition();
                        mobile = customGroupUnionDto.getMobile();
                        sort = customGroupUnionDto.getUserSort();
                        break;
                    default:
                        break;
                }
                Map<String, Object> child = new HashMap<>();
                child.put("id", id);
                child.put("name", name);
                child.put("mobile", mobile);
                child.put("position", position);
                child.put("type", customGroupUnionDto.getType());
                child.put("sort", sort);
                children.add(child);
            }
            customGroupDto.setChildren(children);
            customGroupDtoList.add(customGroupDto);
        }
        return customGroupDtoList;
    }
}
